package com.ruoyi.web.hnsdsa.controller;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.web.hnsdsa.domain.SignStudentApply;
import com.ruoyi.web.hnsdsa.dto.WechatAppLoginDTO;
import com.ruoyi.web.hnsdsa.service.ISignStudentApplyService;
import com.ruoyi.web.hnsdsa.util.CertNumberUtil;
import com.ruoyi.web.hnsdsa.util.DownFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.ruoyi.web.hnsdsa.util.CertNumberUtil.confirmCertNumber;

@RestController
@RequestMapping("/signStudentInSystem")
public class SignStudentController extends BaseController {
    @Autowired
    private ISignStudentApplyService signStudentApplyService;

    @Autowired
    private ServerConfig serverConfig;
    /**
     * 查询报名登记学生列表
     */
    @PreAuthorize("@ss.hasPermi('signStudent:signStudent:list')")
    @GetMapping("/list")
    public TableDataInfo list(SignStudentApply signStudentApply)
    {
        startPage();
        List<SignStudentApply> list = signStudentApplyService.selectSignStudentApplyList(signStudentApply);
        return getDataTable(list);
    }

    /**
     * 导出报名登记学生列表
     */
    @PreAuthorize("@ss.hasPermi('signStudent:signStudent:export')")
    @Log(title = "报名登记学生", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SignStudentApply signStudentApply)
    {
        List<SignStudentApply> list = signStudentApplyService.selectSignStudentApplyList(signStudentApply);
        ExcelUtil<SignStudentApply> util = new ExcelUtil<SignStudentApply>(SignStudentApply.class);
        util.exportExcel(response, list, "报名登记学生数据");
    }

    /**
     * 获取报名登记学生详细信息
     */
    @PreAuthorize("@ss.hasPermi('signStudent:signStudent:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(signStudentApplyService.getById(id));
    }

    /**
     * 新增报名登记学生
     */
    @PreAuthorize("@ss.hasPermi('signStudent:signStudent:add')")
    @Log(title = "报名登记学生", businessType = BusinessType.INSERT)
    @PostMapping("/signStudentApplyPlus")
    public AjaxResult add(@RequestBody SignStudentApply signStudentApply) {
        System.out.println(signStudentApply);
//            1.检查数据
//              1.1库中是否存在以上人员
        List<SignStudentApply> cert_number = signStudentApplyService.list(new QueryWrapper<SignStudentApply>().eq("cert_number", signStudentApply.getCertNumber()));
        Boolean isJoined=true;
        if (cert_number.size()>=1){
            isJoined=true;
            return AjaxResult.error("您已经报过名了");
        }if(cert_number.size()==0){
            isJoined=false;
        }


//              1.2身份证检查

        Boolean aBoolean = CertNumberUtil.certCheck(signStudentApply.getStudentName(), signStudentApply.getCertNumber());
        if (!aBoolean){
            return AjaxResult.error("身份证实名失败");
        }
//              1.3 年龄检查
        int ageByIdCard = IdcardUtil.getAgeByIdCard(signStudentApply.getCertNumber());
        if(ageByIdCard>14){
            return AjaxResult.error("年龄不符合");

        }
//                2.入库
//3.做类型检查 判断是小升初还是初升高

//        signStudentApply.setSignType(1L);



        return toAjax(signStudentApplyService.save(signStudentApply));
    }

    /**
     * 修改报名登记学生
     */
    @PreAuthorize("@ss.hasPermi('signStudent:signStudent:edit')")
    @Log(title = "报名登记学生", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SignStudentApply signStudentApply) {
        return toAjax(signStudentApplyService.updateById(signStudentApply));
    }

    /**
     * 删除报名登记学生
     */
   @PreAuthorize("@ss.hasPermi('signStudent:signStudent:remove')")
    @Log(title = "报名登记学生", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(signStudentApplyService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 身份证号码检查
     * 有成本，需谨慎
     * @return
     */
    public AjaxResult checkCertNumber(String name,String certnumber){

        Boolean aBoolean = CertNumberUtil.certCheck(name, certnumber);

        if (aBoolean){
            return  AjaxResult.success("身份证验证成功");
        }
        return AjaxResult.error("身份证实名失败");

    }

    @GetMapping("searchCertNumber")
    public AjaxResult  searchCertNumber( String certnumber){
        SignStudentApply one = signStudentApplyService.getOne(new QueryWrapper<SignStudentApply>().eq("cert_number", certnumber).eq("sign_type", 1));
        return AjaxResult.success(one);


    }

    @PostMapping("wxLogin")
    public AjaxResult wxLogin(@RequestBody WechatAppLoginDTO wechatAppLoginDTO) {
        String prappid = "wxe0518778c8897a3b";
        String presecret = "a6609bd58dcac2f4a1d582e412dd33e7";
        String getOpenIdUrl = StringUtils.format("https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code", prappid, presecret,
                wechatAppLoginDTO.getCode());
        String result = HttpRequest.get(getOpenIdUrl).contentType("application/json").timeout(20000).execute().body();
        JSONObject sessionKeyJson = JSONUtil.parseObj(result);
        wechatAppLoginDTO.setSessionKey((String) sessionKeyJson.get("session_key"));
        wechatAppLoginDTO.setOpenId((String) sessionKeyJson.get("openid"));
        AES aes = new AES(Mode.CBC.toString(), Padding.PKCS5Padding.toString(), Base64.decode(wechatAppLoginDTO.getSessionKey()), Base64.decode(wechatAppLoginDTO.getIv()));
        String phoneStr = aes.decryptStr(wechatAppLoginDTO.getPhone());
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(phoneStr);
        return AjaxResult.success(jsonObject.getString("phoneNumber"));

    }
    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            System.out.println("filePath"+filePath);
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);

            String url = serverConfig.getUrl() + fileName;

            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);

            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 新增报名登记学生（增强版）
     */
//    @PreAuthorize("@ss.hasPermi('jw:signStudentApply:add')" )
    @Log(title = "报名登记学生", businessType = BusinessType.INSERT)
    @PostMapping("SingleSignStudentApplyPlus")
    public AjaxResult addPlus(@RequestBody SignStudentApply signStudentApply) {

        System.out.println("报名的学生为：" + signStudentApply);
        int i = 0;
        int u = 0;

        LocalDateTime now = LocalDateTimeUtil.now();
        LocalDateTime ruleTimeAMFirst = LocalDateTime.of(2022, 5,24, 0, 0, 00
        );
//
//        if (now.isAfter(ruleTimeAMFirst)){
//
//            return AjaxResult.error("抱歉！已经截止");
//
//        }


        if (signStudentApply.getId() == null || signStudentApply.getId() == 0) {
            System.out.println("新增学生");



            //判断当前是否已经报名
            Long cert_number = signStudentApplyService.count(new QueryWrapper<SignStudentApply>().eq("cert_number", signStudentApply.getCertNumber()));


            Long cert_number2 = signStudentApplyService.count(new QueryWrapper<SignStudentApply>().eq("cert_number", signStudentApply.getCertNumber()));

            if(cert_number2>0){
                return AjaxResult.error("请等待情况说明审核");
            }
            if (cert_number >= 1) {
                return AjaxResult.error("请勿重复提交！");
            }
            i = confirmCertNumber(signStudentApply.getStudentName(), signStudentApply.getCertNumber());

        } else if (signStudentApply.getId() != null || signStudentApply.getId() != 0) {
            System.out.println("修改学生");
            i = 1;
            u = 1;
        }
        if (i != 1) {
            return AjaxResult.error("身份证错误！");
        } else if (i == 1) {
            int age = 0;
            try {
                age = IdcardUtil.getAgeByIdCard(signStudentApply.getCertNumber(), new Date());
            } catch (Exception e) {
                age = 99;
            }
            if (age>10 && age <14){
                //小升初
                signStudentApply.setSignType(1L);
                signStudentApply.setSignNum(1L);
            }else if(age>13 && age<18){
                //初升高
                signStudentApply.setSignType(2L);
                signStudentApply  .setSignNum(1L);
            }else {
                //未知
            }
            if (age > 18 || age < 10) {

                return AjaxResult.error("年龄不符合！");
            }
            int genderByIdCard = IdcardUtil.getGenderByIdCard(signStudentApply.getCertNumber());

            signStudentApply.setAge( Long.valueOf(age));
            signStudentApply    .setGender( Long.valueOf(genderByIdCard));
            String x = signStudentApply.getStudentPhtot();
            if (!x.contains("https://hnsdsa.cn/hnsdsa-api")) {
                String frontPath = "https://hnsdsa.cn/hnsdsa-api";
                String ccc = frontPath + x;
                signStudentApply.setStudentPhtot(ccc);
            }
            if (u == 0) {
                return toAjax(signStudentApplyService.save(signStudentApply) ? 1 : 0);
            } else if (u == 1) {
                return toAjax(signStudentApplyService.updateById(signStudentApply) ? 1 : 0);

            }
        }
        return AjaxResult.error("未知错误！！");
    }
    @RequestMapping("getStudents")
    public AjaxResult getStudents(String certNumber) {

        List<SignStudentApply> cert_number = signStudentApplyService.list(new QueryWrapper<SignStudentApply>().eq("cert_number", certNumber));

        return AjaxResult.success(cert_number);
    }

    @GetMapping("getJoinList")
    public  AjaxResult getJoinList(){

        List<SignStudentApply> list = signStudentApplyService.list();

        return AjaxResult.success(list);
    }

    /**
     * 档案下载
     * @return
     */
    @GetMapping("downloadStudentList")
    public AjaxResult downloadStudentList(){
        List<SignStudentApply> list = signStudentApplyService.list();
        List<String> imagsUrl=new ArrayList<>(list.size());
        list.forEach(item->{
            imagsUrl.add(item.getStudentPhtot());
        });
        String compress = DownFileUtil.compress(imagsUrl);
        return AjaxResult.success(compress);
    }


}
